OpenLayers.Strategy.AttributeCluster = OpenLayers.Class(
		OpenLayers.Strategy.Cluster, {
			/**
			 * the attribute to use for comparison
			 */
			attribute : null,
			/**
			 * Method: shouldCluster Determine whether to include a feature in a
			 * given cluster.
			 * 
			 * Parameters: cluster - {<OpenLayers.Feature.Vector>} A cluster.
			 * feature - {<OpenLayers.Feature.Vector>} A feature.
			 * 
			 * Returns: {Boolean} The feature should be included in the cluster.
			 */
			shouldCluster : function(cluster, feature) {
				var cc_attrval = cluster.cluster[0].attributes[this.attribute];
				var fc_attrval = feature.attributes[this.attribute];
				var superProto = OpenLayers.Strategy.Cluster.prototype;
				var b = cc_attrval === fc_attrval
						&& superProto.shouldCluster.apply(this, arguments);

				return b;

			},
			CLASS_NAME : "OpenLayers.Strategy.AttributeCluster"
		});

var map, sizes, additional_points, lastimagesize, dragFeature, cpopup, wkt, imagenames, vectorlayer, street_data_vector, building_data_vector, visiblefeatures, initialfeatures, currentfeatures, stylemap, select, radius, lastselectedfeature, controller, dragcontriller, markersize, clasterstrategy;

function getImageSizeForZoom(zoomLevel) {
	// var szs = '0-10:30;11-15:35;16-17:45;18:50'.split(';');
	var ret = 20;
	if (zoomLevel >= 0 && zoomLevel <= 10)
		ret = 20;
	if (zoomLevel >= 11 && zoomLevel <= 15)
		ret = 25;
	if (zoomLevel >= 16 && zoomLevel <= 17)
		ret = 30;
	if (zoomLevel >= 18)
		ret = 35;
	ret += 5;
	return ret;
	/*
	 * for (z = 0; z < szs.length; z++) { var sz=szs[z].split(':'); v = {};
	 * v.size=sz[1]; var zooms=szs[z].split('-'); v.start=zooms[0];
	 * if(zooms.length>1) v.end=zooms[1]; if(zoomLevel>=v.start && v.end &&
	 * zoomLevel<=v.end){ return v.size; } }
	 */
	return 30;
}
function initClusterMap(gismap) {
	map = gismap;
	currentfeatures = [];
	initialfeatures = [];
	visiblefeatures = [];
	imagenames = [];
	sizes = [];
	lastimagesize = 0;

	map.events.register("moveend", map, my_moveend_function);
	var styleMap = new OpenLayers.StyleMap({
  'default': new OpenLayers.Style({
    'strokeWidth': 5,
    'strokeColor': '#5555FF',
    strokeDashstyle: 'dashdot'
  })
});
	street_data_vector = new OpenLayers.Layer.Vector("street_data_vector" , {styleMap: styleMap});
	building_data_vector = new OpenLayers.Layer.Vector("street_data_vector");
	map.addLayers([ street_data_vector, building_data_vector ]);
	wkt = new OpenLayers.Format.WKT();
}

function my_moveend_function() {
	var zoom1 = map.getZoom();
	var imageSize = getImageSizeForZoom(zoom1);
	if (lastimagesize != imageSize) {
		lastimagesize = imageSize;
		setmarkersize(imageSize);
		reorderFeatures();
	}
}
function destroyCurrent() {
	currentfeatures = [];
}

function beginDrag() {
	if (dragFeature)
		dragFeature.activate();
	if (select)
		select.deactivate();
}

function stopDrag() {
	if (select)
		select.activate();
	if (dragFeature)
		dragFeature.deactivate();
}

function clearResult() {
	destroyCurrent();
	for ( var i in initialfeatures) {
		currentfeatures[i] = initialfeatures[i];
	}
}

function getCount() {
	var count = 0;
	for ( var i in currentfeatures) {
		if (currentfeatures[i].di_id)
			count++;
	}
	return count;
}

function getImageID(pid) {
	var image_id = -1;
	var f = initialfeatures[pid];
	if (f && f.img_id)
		image_id = f.img_id;
	return image_id;
}

function getImageID(pid) {
	var image_id = -1;
	var f = initialfeatures[pid];
	if (f && f.img_id)
		image_id = f.img_id;
	return image_id;
}

function makeHttpObject() {
	try {
		return new XMLHttpRequest();
	} catch (error) {
	}
	try {
		return new ActiveXObject("Msxml2.XMLHTTP");
	} catch (error) {
	}
	try {
		return new ActiveXObject("Microsoft.XMLHTTP");
	} catch (error) {
	}

	throw new Error("Could not create HTTP request object.");
}

function makerequest(url, fnct) {
	var request = makeHttpObject();
	request.open("GET", url, false);
	request.onreadystatechange = fnct;
	request.send(null);
}

function addPointsStr(s) {
	if (!s)
		return;
	s = s.trim();
	if (s.length = 0)
		return;
	
	var ret = s.split('\n');
	for ( var z = 0; z < ret.length; z++) {
		var data = ret[z].trim().split('#');
		addPoints(data[0].trim(), data[1].trim());
	}
	finishAdding(getImageSizeForZoom(map.getZoom()));
	my_moveend_function();

}

function loadPoints(criteria) {

	destroyCurrent();
	if (vectorlayer)
		reorderFeatures();

	if (additional_points) {
		additional_points = additional_points.trim();
		if (additional_points.length != 0) {
			addPointsStr(additional_points);
		}
	}

	if (!criteria)
		return;
	if (criteria.length == 0)
		return;
	var request = makeHttpObject();

	request.open("GET", "getmappoints.jsp?criteria=" + criteria, false);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var s = request.responseText.trim();

			addPointsStr(s);
		}

	};
	request.send(null);
}

function getImageName(imgid) {
	if (!imagenames)
		imagenames = [];
	if (imagenames[imgid])
		return;
	var request = makeHttpObject();
	request.open("GET", "images/getimagenames.jsp?id=" + imgid, false);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var ret = request.responseText.trim().split(':');
			imagenames[ret[0]] = ret[1];
		}

	};
	request.send(null);
}

function getDistance() {
	var zoom = map.getZoom();
	if (zoom <= 9)
		return 100;
	if (zoom <= 13)
		return 50;
	if (zoom <= 17)
		return 35;
	if (zoom <= 20)
		return 20;
	if (zoom <= 25)
		return 10;
}

function addPoints(imageid, points) {
	getImageName(imageid);
	getImageName('t' + imageid);
	getImageName('d' + imageid);
	var mySplitResult = points.split("-");
	for ( var i = 0; i < mySplitResult.length; i++) {
		var onepoint = mySplitResult[i].split(";");
		var _idM = onepoint[0];
		var _xM = onepoint[1];
		var _yM = onepoint[2];
		var v = initialfeatures[_idM];

		if (!v) {
			v = {};

		}
		v.di_id = _idM;

		v.img_id = imageid;
		v.cx = _xM;
		v.cy = _yM;
		initialfeatures[_idM] = v;
		currentfeatures[_idM] = v;
	}

}

function deletePoint(did) {
	var tmp = [];
	for ( var i in initialfeatures) {
		if (did != i) {
			var v = initialfeatures[i];
			tmp[i] = v;
		}
	}
	initialfeatures = tmp;
	var tmp1 = [];
	for ( var i in currentfeatures) {
		if (did != i) {
			var v = currentfeatures[i];
			tmp1[i] = v;
		}
	}

	currentfeatures = tmp1;

}

function getImageContext(feature) {
	var color = 'images/getimage.jsp?id=';
	var imgid = 44;
	if (feature.attributes.img_id) {
		imgid = feature.attributes.img_id;
	} else if (feature.cluster && feature.cluster.length == 1
			&& feature.cluster[0].attributes.img_id) {
		imgid = feature.cluster[0].attributes.img_id;
	} else {
		if (feature.cluster && feature.cluster.length) {
			var cimg_id = feature.cluster[0].attributes.img_id;
			for ( var j = 1; j <= feature.cluster.length; j++) {
				if (feature.cluster[j] && feature.cluster[j].attributes
						&& feature.cluster[j].attributes.img_id
						&& feature.cluster[j].attributes.img_id != cimg_id) {
					return 'All.png';
				}

			}
			imgid = cimg_id;
			if (feature.cluster.length > 5)
				imgid = "t" + imgid;
			else if (feature.cluster.length > 1)
				imgid = "d" + imgid;
		} else {
			color = 'All.png';
			imgid = '';
		}
	}
	var existstantimage = imagenames[imgid];
	if (existstantimage) {
		return existstantimage;
	} else {
		getImageName(imgid);
		return color + imgid;
	}
}

function createStyleMap() {
	var imgcontextDefault = {
		getIMG : function(feature) {
			return getImageContext(feature);
		},
		getIMGSize : function(feature) {
			return markersize;
		}
	};

	var imgcontextSelect = {
		getIMG : function(feature) {
			return getImageContext(feature);
		},
		getIMGSize : function(feature) {
			if (!feature.attributes.img_id && feature.cluster
					&& feature.cluster.length) {
				if (feature.cluster.length > 1)
					return markersize + markersize * 0.25;
				else
					return markersize + markersize * 0.05;
			}
			return markersize;
		}
	};

	var grStyleDefault = new OpenLayers.Style({
		'externalGraphic' : "${getIMG}",
		'graphicHeight' : "${getIMGSize}",
		'graphicWidth' : "${getIMGSize}",
		'graphicXOffset' : -10.5,
		'graphicYOffset' : -12.5,
		'strokeColor' : '#0000ff',
		'strokeOpacity' : 0.5,
		'strokeWidth' : 5
	}, {
		context : imgcontextDefault
	});
	var grStyleSelect = new OpenLayers.Style({
		'externalGraphic' : "${getIMG}",
		'graphicHeight' : "${getIMGSize}",
		'graphicWidth' : "${getIMGSize}",
		'graphicXOffset' : -10.5,
		'graphicYOffset' : -12.5,
		'strokeColor' : '#0000ff',
		'strokeOpacity' : 0.5,
		'strokeWidth' : 5
	}, {
		context : imgcontextSelect
	});
	// style the vectorlayer
	stylemap = new OpenLayers.StyleMap({
		'default' : grStyleDefault,
		'select' : grStyleSelect
	});
}

function setmarkersize(gismarkersize) {
	markersize = gismarkersize;
	createStyleMap();
	vectorlayer.styleMap = stylemap;
}

function setPopupMargin(popup) {
	// popup.contentDiv.style.overflow='hidden';
	popup.contentDiv.style.padding = '0px';
	popup.contentDiv.style.margin = '0px';
}

function reorderFeatures() {

	clasterstrategy.distance = getDistance();
	// var rf = [];
	// var cb = map.getExtent();
	var af = [];
	// var nvisiblefeatures = [];
	for ( var i in currentfeatures) {
		var cf = currentfeatures[i];
		var _imageid = cf.img_id;
		var _type_id = cf.type_id;
		var p = new OpenLayers.Geometry.Point(cf.cx, cf.cy);
		v = new OpenLayers.Feature.Vector(p, {
			di_id : i,
			img_id : _imageid,
			type_id : _type_id
		});
		af.push(v);
	}

	/*
	 * for ( var i in currentfeatures) {
	 * 
	 * var cf = currentfeatures[i]; var g = new OpenLayers.LonLat(cf.cx, cf.cy);
	 * var vf = visiblefeatures[i]; if (cb.containsLonLat(g)) { // if (!vf) {
	 * var _imageid = cf.img_id; var p = new OpenLayers.Geometry.Point(cf.cx,
	 * cf.cy); v = new OpenLayers.Feature.Vector(p, { di_id : i, img_id :
	 * _imageid }); af.push(v); // } nvisiblefeatures[i] = cf; } else if (vf) {
	 * rf[i] = vf; } }
	 */
	// visiblefeatures = nvisiblefeatures;
	// allfeatures = vectorlayer.features;
	// rffc = [];
	// rffcRemove = [];
	//
	// try {
	// if (allfeatures.length > 0) {
	// for ( var j = 0; j <= allfeatures.length; j++) {
	// var feature = allfeatures[j];
	// if (!feature)
	// continue;
	// if (feature.cluster && feature.cluster.length) {
	// for ( var k = 0; k <= feature.cluster.length; k++) {
	// var ce = feature.cluster[k];
	// rffc.push(ce);
	// }
	// } else {
	// rffc.push(feature);
	// }
	// }
	// if (rffc.length > 0) {
	// for ( var b = 0; b <= rffc.length; b++) {
	// var gg = rffc[b];
	// if (!gg)
	// continue;
	// if (gg.attributes)
	// try {
	// var di_id = gg.attributes['di_id'];
	// if (di_id && rf[di_id])
	// rffcRemove.push(gg);
	// } catch (e) {
	// }
	// }
	// }
	// }
	//
	// } catch (err) {
	// txt = "There was an error on this page.\n\n";
	// txt += "Error description: " + err.description + "\n\n";
	// txt += "Click OK to continue.\n\n";
	// }
	// vectorlayer.removeFeatures(rffcRemove);
	vectorlayer.removeAllFeatures();
	vectorlayer.addFeatures(af);

}

function closePopUp() {
	if (cpopup) {
		cpopup.hide();

	}
}

function showPopup(contentHtml, grap) {

	closePopUp();
	cpopup = new OpenLayers.Popup.FramedCloud("claud", new OpenLayers.LonLat(
			grap.x, grap.y), null, contentHtml, null, true, closePopUp);
	cpopup.autoSize = true;
	map.addPopup(cpopup);
}

function mapZoomToPopup(lon, lat) {
	closePopUp();
	map.setCenter(new OpenLayers.LonLat(lon, lat), map.getZoom() + 2);

}

function featureSelected(img_id, fcount, point_id, grap) {
	// alert(img_id + ' ' + type_id + ' ' + fcount + ' ' + point_id + ' ' +
	// grap);
	var contentHt = "<img src=\"" + imagenames[img_id]
			+ "\" height=\"42\" width=\"42\" />";
	if (fcount > 1) {
		contentHt += "მონიშნული ობიექტების რაოდენობაა:" + fcount
				+ "<p><a href=\"#\" onclick=\"mapZoomToPopup(" + grap.x + ","
				+ grap.y + ");\">გადიდება</a>";

		showPopup(contentHt, grap);
	} else {
		var request = makeHttpObject();
		var recUrl = "getpointinfo.jsp?id=" + point_id + "&type_id=" + img_id;
		request.open("GET", recUrl, false);
		request.onreadystatechange = function() {
			if (request.readyState == 4) {
				var s = request.responseText.trim();
				showPopup(s, grap);
			}

		};
		request.send(null);
	}

}

function alertSelectedFeatures(cluster) {
	var img_id = null;
	var fcount = 0;
	var point_id = null;
	var grap = null;
	var type_id = null;

	if (cluster && cluster.length) {
		for ( var j = 0; j <= cluster.length; j++) {
			if (cluster[j] && cluster[j].attributes
					&& cluster[j].attributes.di_id) {
				img_id = cluster[j].attributes.img_id;
				fcount++;
				point_id = cluster[j].attributes.di_id;
				grap = cluster[j].geometry;
			}
		}
	}

	featureSelected(img_id, fcount, point_id, grap);
	// if(){
	//			
	// }
	if (ids.length = 1 && controller)
		controller(ids);
}

function addWKT(data, data_vector, bounds) {

	var features = wkt.read(data);
	if (features) {
		if (features.constructor != Array) {
			features = [ features ];
		}
		for ( var i = 0; i < features.length; ++i) {
			if (!bounds) {
				bounds = features[i].geometry.getBounds();
			} else {
				bounds.extend(features[i].geometry.getBounds());
			}

		}
		data_vector.addFeatures(features);
		return bounds;
	}
}

function searchStreets(street_name, _buldN) {
	var request = makeHttpObject();
	request.open("GET", "getspatialobjects.jsp?" + street_name + _buldN, false);
	street_data_vector.destroyFeatures();
	building_data_vector.destroyFeatures();
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var s = request.responseText.trim();
			if (!s || s.length == 0)
				return;
			var bounds;
			var data = s.split("\n");
			for ( var z = 0; z < data.length; z++) {
				var data1 = data[z].trim().split(';');
				if (data1[0] == 1) {
					bounds = addWKT(data1[1], street_data_vector, bounds);
				} else
					bounds = addWKT(data1[1], building_data_vector, bounds);
			}
			if (bounds)
				map.zoomToExtent(bounds);
		}

	};
	request.send(null);
}

function searchStreetsAndPoints(obj_name, _object_type_val, street_name, _buldN) {
	var request = makeHttpObject();
	request.open("GET", "getmappoints.jsp?" + street_name + _buldN + obj_name
			+ _object_type_val, false);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var s = request.responseText.trim();
			additional_points = s;
			operatewithItems('');
		}

	};
	request.send(null);
}

function searchDataByCriteria() {
	var obj_name = a.el.val();
	if (obj_name && obj_name.length > 0)
		obj_name = "&obj_name=" + obj_name;
	if (!obj_name)
		obj_name = "";
	var street_name = a1.el.val();
	if (street_name && street_name.length > 0)
		street_name = "&street_name=" + street_name;
	if (!street_name)
		street_name = "";
	var myTextField = document.getElementById('buldN');
	var _buldN = myTextField.value;
	if (_buldN && street_name.length > 0)
		_buldN = "&buildNo=" + _buldN;
	if (!_buldN)
		_buldN = "";

	var _object_type_val = object_type_val;
	if (_object_type_val)
		_object_type_val = "&object_type=" + _object_type_val;
	if (!_object_type_val)
		_object_type_val = "";

	searchStreets(street_name, _buldN);
	searchStreetsAndPoints(obj_name, _object_type_val, street_name, _buldN);

}

function finishAdding(gismarkersize) {
	markersize = gismarkersize;
	if (vectorlayer) {
		reorderFeatures();
		return;
	}
	// var alertFeature = function

	// var doubleClicked = function(evt) {
	// if (!lastselectedfeature || lastselectedfeature == null)
	// return;
	//
	// var feature = lastselectedfeature;
	// lastselectedfeature = null;
	// if (feature.cluster) {
	// if (feature.attributes.count > 0) {
	// map.zoomIn();
	// return;
	// }
	// }

	// };

	var strategies = [];
	clasterstrategy = new OpenLayers.Strategy.AttributeCluster({
		attribute : 'img_id'
	});

	strategies.push(clasterstrategy);

	createStyleMap();

	vectorlayer = new OpenLayers.Layer.Vector('Vectorlayer', {
		styleMap : stylemap,
		strategies : strategies
	});
	select = new OpenLayers.Control.SelectFeature(vectorlayer, {
		clickout : true,
		toggle : false,
		multiple : false,
		hover : false,
		toggleKey : "ctrlKey", // ctrl key removes from
		// selection
		multipleKey : "shiftKey" // shift key adds to selection
	});
	map.addLayer(vectorlayer);
	map.addControl(select);
	dragFeature = new OpenLayers.Control.DragFeature(vectorlayer, {
		onStart : function(feature, pixel) {
			if (feature.cluster && feature.cluster.length
					&& feature.cluster.length > 1) {
				dragFeature.deactivate();
				dragFeature.activate();
			}
		},
		onComplete : function(feature, pixel) {
			if (feature.cluster && feature.cluster.length
					&& feature.cluster.length == 1
					&& feature.cluster[0].attributes
					&& feature.cluster[0].attributes.di_id) {
				var lonLat = map.getLonLatFromPixel(pixel);
				var di_id = feature.cluster[0].attributes.di_id;
				var pointStr = "";
				pointStr = di_id + ";";
				pointStr += lonLat.lon + ";";
				pointStr += lonLat.lat + ";";
				pointStr += "0";
				dragcontriller(pointStr);
			}
		}
	});
	map.addControl(dragFeature);
	select.activate();

	vectorlayer.events.on({
		'featureselected' : function(obj) {
			lastselectedfeature = null;

			if (obj.feature.cluster) {
				lastselectedfeature = obj.feature;
				// alert(lastselectedfeature+' '+lastselectedfeature.cluster);
				alertSelectedFeatures(lastselectedfeature.cluster);
			}
		},
		'featureunselected' : function(obj) {
			closePopUp();
		}
	});

	reorderFeatures();

}
